#include "stm32f10x.h"                  // Device header
#include <stdio.h>
#include <stdarg.h>

void Serial_Init()
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);					//开启USART1的时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);					//开启GPIOA的时钟

	GPIO_InitTypeDef GPIO_InitStructure;
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;     					//模拟输出
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Pin =GPIO_Pin_9;
 	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	
	USART_InitTypeDef USART_InitStruct;	
	USART_InitStruct.USART_BaudRate = 9600;																								//波特率为9600
	USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;          //无流控制
	USART_InitStruct.USART_Mode = USART_Mode_Tx;                                          //发送模式
	USART_InitStruct.USART_Parity = USART_Parity_No;                                      //无校验
	USART_InitStruct.USART_StopBits = USART_StopBits_1;                                   //停止为一位
	USART_InitStruct.USART_WordLength = USART_WordLength_8b;                              //一帧八位
	USART_Init(USART1,&USART_InitStruct);
	
	USART_Cmd(USART1,ENABLE);
}

void Serial_SendByte(uint8_t byte)
{
	USART_SendData(USART1,byte);																			//根据配置把一字节的数据从发送移位寄存器中移出
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE) == RESET);				//等待发送移位寄存器移完数据
}

void Serial_SendArray(uint8_t *Array, uint16_t Length)
{
	int i = 0;
	for(i = 0;i<Length;i++)
	{
		Serial_SendByte(Array[i]);
	}
}

void Serial_SendString(char *String)
{
	while(*String)
	{
		Serial_SendByte(*String);
		String++;
	}
}

void Serial_SendNumber(uint32_t Number)
{
	if(Number <=0)
	{
		return;
	}
	if(Number < 10)
	{
		Serial_SendByte(Number + '0');
	}
	else
	{
		Serial_SendNumber(Number/10);
		Serial_SendByte(Number%10 + '0');
	}
}

int fputc(int ch,FILE *f)
{
	Serial_SendByte(ch);
	return ch;
}

void Serial_Printf(char *format,...)
{
	char String[100];
	va_list arg;
	va_start(arg,format);
	vsprintf(String,format,arg);
	va_end(arg);
	Serial_SendString(String);
}